package com.activemq;

import cn.hutool.core.exceptions.ExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.boot.autoconfigure.jms.JmsProperties;

import javax.jms.*;

/**
 * 通过监听的方式来消费消息
 */
@Slf4j
public class TestConsumerWithListener {
    public static void main(String[] args) throws Exception {
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(MqHelloWorld.URL);
        Connection connection = factory.createConnection();
        connection.start();
        Session session = connection.createSession(false, JmsProperties.AcknowledgeMode.AUTO.getMode());
        Queue queue = session.createQueue(MqHelloWorld.QUEUE);
        MessageConsumer consumer = session.createConsumer(queue);
        consumer.setMessageListener(message -> {
            if (!(message instanceof TextMessage)) {
                return;
            }
            try {
                log.error("消费者1：" + ((TextMessage) message).getText());
            } catch (JMSException e) {
                throw ExceptionUtil.wrapRuntime(e);
            }
        });
        System.in.read();
        consumer.close();
        session.close();
        connection.close();
    }
}

/**
 * 第二个消费者
 */
@Slf4j
class OtherConsumer {
    public static void main(String[] args) throws Exception {
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(MqHelloWorld.URL);
        Connection connection = factory.createConnection();
        connection.start();
        Session session = connection.createSession(false, JmsProperties.AcknowledgeMode.AUTO.getMode());
        Queue queue = session.createQueue(MqHelloWorld.QUEUE);
        MessageConsumer consumer = session.createConsumer(queue);
        consumer.setMessageListener(message -> {
            if (!(message instanceof TextMessage)) {
                return;
            }
            try {
                log.error("消费者2：" + ((TextMessage) message).getText());
            } catch (JMSException e) {
                throw ExceptionUtil.wrapRuntime(e);
            }
        });
        System.in.read();
        consumer.close();
        session.close();
        connection.close();
    }
}
